require "net/http"
require "uri"
require "rubygems"
require 'xmlsimple'

class EventsController < ApplicationController
  # GET /events
  # GET /events.json
  def index
    @events = Event.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @events }
    end
  end

  # GET /events/1
  # GET /events/1.json
  def show
    @event = Event.find(params[:id])
	
    respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @event }
    end
  end

  # GET /events/new
  # GET /events/new.json
  def new
    @event = Event.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @event }
    end
  end

  # GET /events/1/edit
  def edit
    @event = Event.find(params[:id])
  end

  # POST /events
  # POST /events.json
  def create
    @event = Event.new(params[:event])
    @event.author_id = session[:user].id

    respond_to do |format|
      if @event.save
        format.html { redirect_to '/event/location/?id='+@event.id.to_s, :notice => 'Event was successfully created.' }
        format.json { render :json => @event, :status => :created }
      else
        format.html { render :action => "new" }
        format.json { render :json => @event.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /events/1
  # PUT /events/1.json
  def update
    @event = Event.find(params[:id])

    respond_to do |format|
      if @event.update_attributes(params[:event])
        format.html { redirect_to @event, :notice => 'Event was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render :action => "edit" }
        format.json { render :json => @event.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /events/1
  # DELETE /events/1.json
  def destroy
    @event = Event.find(params[:id])
    @event.destroy

    respond_to do |format|
      format.html { redirect_to events_url }
      format.json { head :no_content }
    end
  end
    	
		'''
	def location
		@location = Location.new
		
		respond_to do |format|
			format.html # new.html.erb
			format.json { render :json => @location }
		end
	end
	'''
	
	def locationInsert
		if request.post?
			@location = Location.new(params[:location])
			url = params[:url]
            url_params = Rack::Utils.parse_query URI(url).query
            eid = url_params['id']
			@location.event_id=eid.to_i
			respond_to do |format|
			l = @location
			
			params=String.new<<(@location.addressName == ""? "":"#{@location.addressName},")
			params = params<<(@location.addressLn1 == ""? "":"#{@location.addressLn1},")
			params = params<<(@location.addressLn2 == ""? "":"#{@location.addressLn2},")<<(@location.city == ""? "":"#{@location.city},")
			params = params<<(@location.stateCode == ""? "":"#{@location.stateCode},")<<(@location.zipCode == ""? "":"#{@location.zipCode},")
			params = params.chop
			
			
			address = params.gsub(" ","+").gsub("|","%7C")
			
			
			geocoderURI = URI.parse("http://maps.googleapis.com/maps/api/geocode/xml?address="<<address<<"&sensor=false")
			http = Net::HTTP.new(geocoderURI.host, geocoderURI.port)
			request = Net::HTTP::Get.new(geocoderURI.request_uri)
			response = http.request(request)			
			if response.code != "200"
				redirect_to '/event/location/?id='+eid, :notice => "Connection Error, responce.code="<<response.code
				return
			end
			xml_data = response.body;
			data = XmlSimple.xml_in(xml_data, { 'KeyAttr' => 'name' })
			if data['status'].to_s.gsub(/\[|\]|"/, '')   == "ZERO_RESULTS"
				redirect_to '/event/location/?id='+eid, :notice => 'Could not find location, try again.'
				return
			end
			
			lat = data['result'][0]['geometry'][0]['location'][0]['lat'].to_s.gsub(/\[|\]|"/, '')
			lon = data['result'][0]['geometry'][0]['location'][0]['lng'].to_s.gsub(/\[|\]|"/, '')
			mapWt = "500"
			mapHt = "400"
			mapImgSrc = "http://maps.googleapis.com/maps/api/staticmap?"<< "markers=color:blue|label:"
			mapImgSrc = mapImgSrc<<@location.locationName.gsub(" ","+").gsub("|","%7c")<<"|" 
			mapImgSrc = mapImgSrc<<lat<<","<<lon<<"&zoom=14&size=" 
			mapImgSrc = mapImgSrc<<mapWt<<"x"<<mapHt<<"&sensor=false"
			mapImgSrc = mapImgSrc.gsub(" ","+").gsub("|","%7c")
			@location.gmapString = mapImgSrc
			
			
				if @location.save

                format.html { redirect_to "/event/invite/?id="+eid, :notice => 'Location was successfully created.' }
					else
						print "\n\n\n\nfailed\n\n\n\n" 
						format.html { redirect_to '/event/location/?id='+eid, :notice => "Failed to save location"}
                    format.json { render :json => @location.errors, :status => :unprocessable_entity }
				end
			end
		end	
	end
    
    def invitePeople
        if request.post?
            @array = params[:invitees]
            url = params[:url]
            url_params = Rack::Utils.parse_query URI(url).query
            eid = url_params['id'].to_i
            @array.each_key do |id|
                @inviteeList = InviteeList.new(:user_ids => id, :event_id => eid)
                if !@inviteeList.save
                    flash[:warning] = "Inviting unsuccessful"
                    redirect_to invite_url
                end
            end
            flash[:message] = "Inviting successful"
            redirect_to events_path
        end
    end   
    
    def checkAttendence
        success = true
        if request.post?
            @array = params[:invitees]
            eid = params[:eid]
            @array.each_key do |id|
                @invitee = InviteeList.find(:first, :conditions => ["user_ids = ? AND event_id = ?",id, eid])                
                if @invitee != nil
                    @invitee.attended = true
                    if !@invitee.save
                        success = false
                    end
                end
            end    
            @invitees = InviteeList.find(:all, :conditions => ["event_id = ?", eid])  
            @invitees.each do |inv|
                if !(@array.key? inv.user_ids.to_s)
                    inv.attended = false
                    inv.save
                end
            end
            if success    
                flash[:message] = "Attendence Update Successful"
                redirect_to '/events/'+eid.to_s
            else
                flash[:warning] = "Attendence Update Unsuccessful"
                redirect_to events_url
            end
        end
    end  
    
end
